import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:www.znpigai.teacher/global_store/action.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/global_store/store.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<HomeState> buildEffect() {
  return combineEffects(<Object, Effect<HomeState>>{
    Lifecycle.initState: _onInit,
    HomeAction.onChangeTab: _onChangeTab,
  });
}

void _onInit(Action action, Context<HomeState> ctx) async {
  Future.delayed(Duration.zero, () async {
    var url = "/correct/${GlobalState.userRole}/api/profile.mvc";
    var result = await Http.get(url);

    if (result.success) {
      GlobalStore.store
          .dispatch(GlobalActionCreator.onChangeUserInfo(result.data));
    } else {
      Util.alertFail(result, ctx.context);
    }
  });
}

void _onChangeTab(Action action, Context<HomeState> ctx) async {
  int index = action.payload;
  if (GlobalState.userRole == 'teacher' && index == 2) {
    List<dynamic> classList = ctx.state.userInfo['classList'];
    if (classList?.isNotEmpty == true) {
      Navigator.of(ctx.context).pushNamed(Nav.HOMEWORK_POST);
    } else {
      Util.alert('还没有班级，无法布置作业', ctx.context);
    }
  } else {
    ctx.dispatch(HomeActionCreator.tab(index));
  }
}
